package com.cn.lxz.lot.http

import android.util.Log
import cn.netdiscovery.http.extension.coroutines.flowPost
import com.bytedance.speech.speechdemo.http.MessageResult
import com.cn.lxz.lot.http.HttpFunction.Companion.runMapGson
import kotlinx.coroutines.runBlocking

object HttpManager {
    const val LLM_URL = "https://ark.cn-beijing.volces.com/api/v3/chat/completions"
    const val CONTENT_TYPE = "application/json"
    const val LLM_KEY = "Bearer 9537f370-abb9-4ff0-ae08-6b721cea9997"
    const val MODEL = "ep-20240729205423-wtj79"
    const val HEADER = "You are a helpful assistant"
    const val STREAM = false

    fun httpLLM(content:String,callBack:(MessageResult)->Unit,errorAction: (Exception)->Unit){
        Thread {
            runBlocking {
                httpClient.flowPost {
                    url {
                        url = LLM_URL
                    }
                    header {
                        "Content-Type" to CONTENT_TYPE
                        "Authorization" to LLM_KEY
                    }
                    body(CONTENT_TYPE) {
                        json {
                            "model" to MODEL
                            "messages" to arrayListOf(
                                json {
                                    "role" to "system"
                                    "content" to HEADER
                                },
                                json {
                                    "role" to "user"
                                    "content" to content
                                }
                            )
                            "stream" to STREAM
                        }
                    }
                }

                    .runMapGson<MessageResult> {
                        try {
                            callBack.invoke(it)
                        } catch (e: Exception) {
                            e.printStackTrace()
                            errorAction.invoke(e)
                        }
                        Log.e("http", it.toString())
                    }

            }
        }.start()
    }

}